package controllers

import (
	"fmt"
	"regexp"
	"strings"
	"t11Lib/t11Errors"
	"t11Lib/t11Log"
	"t11Lib/t11Util"
	"time"
	"亚太-iot-服务器/biz"
	"亚太-iot-服务器/biz/mqtt"
	"亚太-iot-服务器/conf"
)

type GatewayController struct {
	BaseController
}

//@router /getTime [get]
func (self *GatewayController) GetTime() {
	self.RetOkJson(time.Now().Unix())
}

var macAddrRegex = regexp.MustCompile(`^[A-Fa-f0-9]{12}$`)

//根据gatewayId和factoryKey，判断网关签名是否正确
//返回网关Id以及error
func (self *GatewayController) checkSign() (string, t11Errors.T11Error) {
	///gateway2/gateway/getConnectInfo?gatewayId=${gatewayId}&sign=${sign}
	gatewayId := self.GetString("gatewayId")
	if !macAddrRegex.MatchString(gatewayId) {
		return "", t11Errors.New("非法的mac地址")
	}
	t := self.GetString("time")
	if _t, e := t11Util.ParseUnixTimeStamp(t); e != nil {
		return "", t11Errors.New("非法的时间")
	} else {
		if _t.Add(time.Minute*5).Before(time.Now()) || _t.Add(-time.Minute*5).After(time.Now()) {
			return "", t11Errors.New("时间戳已经过时")
		}
	}

	sign := strings.ToUpper(self.GetString("sign"))
	signStr := fmt.Sprintf("%v%v%v", conf.AppConfig.MqttFactoryKey, gatewayId, t)
	t11Log.Debuglnf("signStr = %v", signStr)
	calcedSign := t11Util.BytesToHexStringWithoutSpace(t11Util.Md5([]byte(signStr)))
	if sign != calcedSign {
		return "", t11Errors.New("非法的签名")
	}
	t11Log.Debuglnf("网关api签名检查：sign = %v, calcedSign = %v", sign, calcedSign)
	return strings.ToUpper(gatewayId), nil
}

//@router /GetConnectInfo [get]
func (self *GatewayController) GetConnectInfo() {
	gatewayId, err := self.checkSign()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	//TODO:检查网关ID是否在数据库中存在
	info, err := mqtt.AccountBiz.GetMqAccount(gatewayId)
	ret := map[string]interface{}{
		"account":   info,
		"sendTopic": fmt.Sprintf("/%v/fromDev/%v", mqtt.ClientToIdx(gatewayId), gatewayId),
		"recvTopic": fmt.Sprintf("/%v/toDev/%v", mqtt.ClientToIdx(gatewayId), gatewayId),
	}
	self.RetJson(ret, err)
}

//长按按钮时重置网关
//@router /reset [get]
func (self *GatewayController) Reset() {
	gwId, err := self.checkSign()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	self.RetStatusJson(biz.GatewayBiz.Reset(self.GetDbConn(), gwId))
}

//重置并注册网关
//@router /resetAndRegister [get]
func (self *GatewayController) ResetAndRegister() {
	gwId, err := self.checkSign()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	wxUser := self.GetString("wxUser")
	tk := biz.UserIdCache.GetUserById(wxUser)
	if tk == nil {
		self.RetStatusJson(t11Errors.New("非法的用户Id"))
		return
	}

	t11Log.Debuglnf("=================user = %v", tk)
	//网关与微信用户建立绑定关系
	self.RetStatusJson(biz.GatewayBiz.ResetAndRegister(self.GetDbConn(), gwId, tk))
}
